import * as mars3d from "mars3d";
import { Viewer } from "mars3d-cesium";

export default class mapPlus {
    Json: any;
    id: string | Viewer;
    map: mars3d.Map;
    eventTarget: mars3d.BaseClass;   //事件对象
    cartographic: mars3d.LngLatPoint; //相机实时坐标
    graphicLayer: mars3d.layer.GraphicLayer;
    Cesium: typeof mars3d.Cesium;
  Wall: any;
  

  constructor(Json:string,id:string | Viewer) {
    
    this.Json = Json
    this.id = id
    this.eventTarget = new mars3d.BaseClass() // 事件机制
    this.Cesium = mars3d.Cesium;

    this.init();
  }
  async init() {
    // Map地图构造参数
    let mapOptions = await mars3d.Util.fetchJson({ url: this.Json });
    // 初始化地图
    this.map =  new mars3d.Map(this.id, mapOptions);




    // 针对不同终端的优化配置
    this.PCBroswer()

    // map构造完成后的一些处理
    // 开场动画
    this.startAnimation()

    // 监听地图的一些事件
    this.mapEvent()

    // 创建矢量图层
    this.marsOnload()

    
  }


  mapEvent() {
        // 监听自带鼠标右键控件结果
        this.map.on(mars3d.EventType.drawCreated, function (event) {
          const graphic = event.graphic;
          console.log('绘制完成:', graphic);
      
          // 判断图形类型
          switch (graphic.type) {
            case 'point':
              console.log('标点结果:', graphic.position);
              break;
            case 'polyline':
              console.log('画线结果:', graphic.positions);
              break;
            case 'polygon':
              console.log('多边形结果:', graphic.positions);
              break;
            case 'rectangle':
              console.log('矩形结果:', graphic.positions);
              break;
            case 'circle':
              console.log('圆形结果:', graphic.position, graphic.radius);
              break;
          }
      
          // 转换为GeoJSON
          const geojson = graphic.toGeoJSON();
          console.log('GeoJSON格式:', geojson);
        });
      
        // 监听相机变化，实时获取坐标
        // 方法1：mars3d.EventType.postRender（最高实时性）
        // 方法2：mars3d.EventType.cameraChanged
        this.map.on(mars3d.EventType.cameraChanged, (event) => {
          const cameraPosition = this.map.camera.position;
      
          // 转换为经纬度
          this.cartographic = mars3d.LngLatPoint.fromCartesian(cameraPosition);
          console.log("相机实时坐标:", this.cartographic);
        });
  
        // 打开了popup(全局监听)
        this.map.on(mars3d.EventType.popupOpen, function (event) {
          const container = event.container // popup对应的DOM
          console.log("打开了popup(全局监听)", event)
        })
        // 关闭了popup(全局监听)
        this.map.on(mars3d.EventType.popupClose, function (event) {
          const container = event.container // popup对应的DOM
          console.log("关闭了popup(全局监听)", event)
        })
    
  }


  PCBroswer() {
      // 针对不同终端的优化配置
  if (mars3d.Util.isPCBroswer()) {
    this.map.zoomFactor = 2.0; // 鼠标滚轮放大的步长参数

    // IE浏览器优化
    if (window.navigator.userAgent.toLowerCase().indexOf("msie") >= 0) {
      this.map.viewer.targetFrameRate = 20; // 限制帧率
      this.map.scene.requestRenderMode = false; // 取消实时渲染
    }
  } else {
    this.map.zoomFactor = 5.0; // 鼠标滚轮放大的步长参数

    // 移动设备上禁掉以下几个选项，可以相对更加流畅
    this.map.scene.requestRenderMode = false; // 取消实时渲染
    this.map.scene.fog.enabled = false;
    this.map.scene.skyAtmosphere.show = false;
    this.map.scene.globe.showGroundAtmosphere = false;
  }

  // 二三维切换不用动画
  if (this.map.viewer.sceneModePicker) {
    this.map.viewer.sceneModePicker.viewModel.duration = 0.0;
  }
  }


  startAnimation() {
    this.map.flyHome({ duration: 0 })

    // 开场动画
    this.map.openFlyAnimation({
      // duration1:4,
      // easingFunction1: Cesium.EasingFunction.QUINTIC_IN_OUT,
    }).then(() => {
      // 动画播放完成后回调
    })
  }

  stopAnimation() {
    this.map.camera.cancelFlight()
  }

 // 组件卸载之前销毁mars3d实例
 destroy() {
    if (this.map) {
      this.map.destroy();
      this.map = null;
    }
    console.log("map销毁完成", this.map);
  }

  
  marsOnload() {
    this.graphicLayer = new mars3d.layer.GraphicLayer();
    this.map.addLayer(this.graphicLayer);
  
    // 对矢量数据绑定事件
    // 2.在layer上绑定监听事件
    this.graphicLayer.on(mars3d.EventType.click,  (event: any) => {
      console.log("监听layer，单击了矢量对象", event);
      this.eventTarget.fire("tapLayer", { text: '6666' })
  
    });

    this.graphicLayer.on(mars3d.EventType.mouseOver, function (event: any) {
      console.log("监听layer，鼠标移入了矢量对象", event);
    });

    this.graphicLayer.on(mars3d.EventType.mouseOut, function (event: any) {
      console.log("监听layer，鼠标移出了矢量对象", event);
    });
  
    // 可在图层绑定右键菜单,对所有加到这个图层的矢量数据都生效
    this.graphicLayerMenu()
  

    
    this.addLabelEntityGraphic(this.graphicLayer)   // 添加文字
    this.addPointEntityGraphic(this.graphicLayer)   // 添加点
    this.addBillboardGraphic(this.graphicLayer)     // 添加图标



  };
  

  graphicLayerMenu() {
    
    // 可在图层绑定右键菜单,对所有加到这个图层的矢量数据都生效
    this.graphicLayer.bindContextMenu([
      {
        text: "删除对象",
        iconCls: "fa fa-trash-o",
        // iconCls: img,
        callback: (e: any)=> {
          const graphic = e.graphic;
          if (graphic) {
            this.graphicLayer.removeGraphic(graphic);
          }
        },
      },
    ]);

}


  
  addLabelEntityGraphic (graphicLayer: mars3d.layer.GraphicLayer){
    const graphic = new mars3d.graphic.LabelEntity({
      position: new mars3d.LngLatPoint(118.853228, 32.043092, 9659),
      style: {
        text: "添加文字",
        font_size: 25,
        font_family: "楷体",
        color: "red",
        outline: true,
        outlineColor: "#bfbfbf",
        outlineWidth: 2,
        horizontalOrigin: this.Cesium.HorizontalOrigin.CENTER,
        verticalOrigin: this.Cesium.VerticalOrigin.BOTTOM,
        visibleDepth: false,
      },
      attr: { remark: "示例1" },
    });
    graphicLayer.addGraphic(graphic);
  }


  addPointEntityGraphic (graphicLayer: mars3d.layer.GraphicLayer)  {
    const graphic = new mars3d.graphic.PointEntity({
      position: [116.2, 31.0, 1000],
      style: {
        color: "#ff0000",
        pixelSize: 10,
        outline: true,
        outlineColor: "#ffffff",
        outlineWidth: 2,
      },
      attr: { remark: "示例2" },
    });
    graphicLayer.addGraphic(graphic);
  }


  addBillboardGraphic(graphicLayer: mars3d.layer.GraphicLayer){
    const graphic = new mars3d.graphic.BillboardEntity({
      name: "贴地图标",
      position: [118.803228, 32.043092, 1000],
      style: {
        // image: "//data.mars3d.cn/img/marker/mark-blue.png",
        // image: "./img/cat.png",
        image: "http://tsconfigserver-cdn.xiangtatech.com/admin/resource/jssgg/jd_1660125955055.png",
        scale: 0.51,
        horizontalOrigin: this.Cesium.HorizontalOrigin.CENTER,
        verticalOrigin: this.Cesium.VerticalOrigin.BOTTOM,
        clampToGround: true,
      },
      attr: { remark: "我是图标" },
    });


    graphic.bindPopup(
      function (event) {
        const attr = event.graphic.attr
        return "我是layer上绑定的自定义模版Popup<br />" + attr.type
      },
      {
        template: `<div class="marsBlackPanel animation-spaceInDown">
                        <div style="background-color:red" class="marsBlackPanel-text">{content}</div>
                        <span class="mars3d-popup-close-button closeButton" >×11</span>
                      </div>`,
        horizontalOrigin: this.Cesium.HorizontalOrigin.LEFT,
        verticalOrigin: this.Cesium.VerticalOrigin.CENTER
      }
    )

    graphic.on(mars3d.EventType.popupOpen, function (event) {
      const container = event.container // popup对应的DOM
      console.log("图层上打开了popup", container)
    })
    graphic.on(mars3d.EventType.popupClose, function (event) {
      const container = event.container // popup对应的DOM
      console.log("图层上移除了popup", container)
    })


    graphicLayer.addGraphic(graphic);
  }


  addWallGraphic(graphicLayer: mars3d.layer.GraphicLayer) {
    if (this.Wall) return
    this.Wall = new mars3d.graphic.WallEntity({
      positions: [[117.07276, 31.649545, 30.3], [117.075171, 31.651865, 25.8], [117.072981, 31.653915, 29.1], [117.082051, 31.660347, 29.8], [117.08961, 31.65404, 30.4], [117.088562, 31.650563, 25.9], [117.083638, 31.644256, 24.3], [117.080782, 31.64316, 29.4], [117.072749, 31.649653, 27.9]],
      style: {
        closure: true,
        diffHeight: 500,
        // 动画线材质
        materialType: mars3d.MaterialType.LineFlow,
        materialOptions: {
          image: "//data.mars3d.cn/img/textures/fence.png",
          color: "#98fdfe",
          speed: 10,
          axisY: true,
          flowDirection: 1  // 默认自下而上
        },
      },
      attr: { remark: "我是墙" },
    });
    graphicLayer.addGraphic(this.Wall); // 还可以另外一种写法: graphic.addTo(graphicLayer)
  }




}